import { ConfigService } from '../../../../core/common/config.service';
import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { Http } from '@angular/http';
import { ECharts } from 'echarts-ng2';
import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: 'app-managerportal',
    templateUrl: './manager-portal.component.html',
    styleUrls: ['./manager-portal.component.scss']
})
export class ManagerPortalComponent implements OnInit, OnDestroy {
    @ViewChild('monthIncome') monthIncome: ECharts;
    @ViewChild('nodeStatist') nodeStatist: ECharts;
    @ViewChild('regionSaleStatist') regionSaleStatist: ECharts;
    @ViewChild('industryRank') industryRank: ECharts;
    @ViewChild('productRank') productRank: ECharts;
    @ViewChild('productSaleStatist') productSaleStatist: ECharts;

    // 渠道销售数据对比
    public datas_chn_sal_cmp = [];
    // 月度收入
    public datas_mon_inc = {
        title: {
            // x: 'center',
            text: '',
            textStyle: { color: '#2D9ED5', fontSize: 18 },
        },
        tooltip: {
            trigger: 'axis',
        },
        grid: {
            left: '4%',
            // right: '4%',
            containLabel: true
        },
        legend: {
            data: []
        },
        toolbox: {
            show: true,
            orient: 'vertical',
            feature: {
                mark: { show: true },
                dataView: { show: true, readOnly: false },
                magicType: { show: true, type: ['line', 'bar'] },
                saveAsImage: { show: true }
            }
        },
        calculable: true,
        xAxis: [
            {
                type: 'category',
                boundaryGap: false,
                data: []
            }
        ],
        yAxis: [
            {
                type: 'value'
            }
        ],
        series: [
            {
                name: '',
                type: 'line',
                smooth: false,
                itemStyle: { normal: { color: '#A1CEEA', areaStyle: { type: 'default' } } },
                data: []
            }
        ]
    };
    // 战区销售量统计
    public datas_reg_sal_stc = {
        title: {
            x: 'left',
            text: '',
            textStyle: { color: '#2D9ED5', fontSize: 18 },
            subtext: '',
        },
        tooltip: {
            trigger: 'item'
        },
        toolbox: {
            show: true,
            feature: {
                dataView: { show: true, readOnly: false },
                restore: { show: true },
                saveAsImage: { show: true }
            },
            iconStyle: { normal: { color: 'default' } }
        },
        calculable: true,
        grid: {
            borderWidth: 0,
            y: 80,
            y2: 60
        },
        xAxis: [
            {
                type: 'category',
                show: false,
                data: []
            }
        ],
        yAxis: [
            {
                type: 'value',
                show: false
            }
        ],
        series: [
            {
                name: '',
                type: 'bar',
                itemStyle: {
                    normal: {
                        color: function (params) {
                            const colorList = [
                                '#C1232B', '#B5C334', '#FCCE10', '#E87C25', '#27727B',
                                '#FE8463', '#9BCA63', '#FAD860', '#F3A43B', '#60C0DD',
                                '#D7504B', '#C6E579', '#F4E001', '#F0805A', '#26C0C0'
                            ];
                            return colorList[params.dataIndex];
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{b}\n{c}'
                        }
                    }
                },
                data: []
            }
        ]
    };
    // 行业排名
    public datas_idt_rank = {
        title: {
            text: '',
            textStyle: { color: '#2D9ED5', fontSize: 18 },
        },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [
            {
                name: '',
                type: 'pie',
                radius: ['32%', '46%'],
                label: {
                    normal: {
                        show: true,
                        position: 'top'
                    }
                },
                labelLine: {
                    normal: {
                        show: true,
                        length: 15
                    }
                },
                data: []
            }
        ]
    };
    // 产品排名
    public datas_pdt_rank = {
        title: {
            text: '',
            textStyle: { color: '#2D9ED5', fontSize: 18 }
        },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [
            {
                name: '',
                type: 'pie',
                selectedMode: 'single',
                radius: [0, '30%'],

                label: {
                    normal: {
                        position: 'inner'
                    }
                },
                labelLine: {
                    normal: {
                        show: false,
                    }
                },
                data: []
            },
            {
                name: '',
                type: 'pie',
                radius: ['40%', '55%'],
                labelLine: {
                    normal: {
                        show: true,
                        length: 10
                    }
                },
                data: []
            }
        ]
    };

    // 产品销售量统计
    public datas_pdt_sal_stc = {
        title: {
            // x: 'center',
            text: '',
            textStyle: { color: '#2D9ED5', fontSize: 18 }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
            }
        },
        legend: {
            x: '120',
            data: []
        },
        grid: {
            left: '4%',
            // right: '4%',
            containLabel: true
        },
        toolbox: {
            show: true,
            orient: 'vertical',
            x: 'right',
            y: 'center',
            feature: {
                mark: { show: true },
                dataView: { show: true, readOnly: false },
                magicType: { show: true, type: ['line', 'bar', 'stack', 'tiled'] },
                restore: { show: true },
                saveAsImage: { show: true }
            }
        },
        calculable: true,
        xAxis: [
            {
                type: 'category',
                data: []
            }
        ],
        yAxis: [
            {
                type: 'value'
            }
        ],
        series: []
    };
    // 保存说有县级以上城市坐标信息
    public geoCoordMap = {};
    // 客户节点统计
    public option = {
        backgroundColor: '#404a59',
        title: {
            text: '',
            subtext: 'data base on location',
            x: 'left',
            textStyle: {
                color: '#2D9ED5',
                fontSize: 18
            }
        },
        tooltip: {
            trigger: 'item',
            formatter: function (params) {
                return params.name + ' : ' + params.value[2];
            }
        },
        visualMap: {
            min: 0,
            max: 100,
            calculable: true,
            inRange: {
                color: ['#50a3ba', '#eac736', '#d94e5d']
            },
            textStyle: {
                color: '#fff'
            }
        },
        geo: {
            map: 'china',
            label: {
                emphasis: {
                    show: false
                }
            },
            itemStyle: {
                normal: {
                    areaColor: '#323c48',
                    borderColor: '#111'
                },
                emphasis: {
                    areaColor: '#2a333d'
                }
            }
        },
        series: [
            {
                name: 'pm2.5',
                type: 'scatter',
                coordinateSystem: 'geo',
                data: this.convertData([]),
                symbolSize: 12,
                label: {
                    normal: {
                        show: false
                    },
                    emphasis: {
                        show: false
                    }
                },
                itemStyle: {
                    emphasis: {
                        borderColor: '#fff',
                        borderWidth: 1
                    }
                }
            }
        ]
    };
    public convertData(data) {
        const res = [];
        for (let i = 0; i < data.length; i++) {
            const geoCoord: any = this.geoCoordMap[data[i].name];
            if (geoCoord) {
                res.push({
                    name: data[i].name,
                    value: geoCoord.concat(data[i].value)
                });
            }
        }
        return res;
    };

    constructor(private http: Http, public configService: ConfigService, private translate: TranslateService) {
        // 获取所有县级市以上城市坐标信息
        this.http.get('assets/cityLocation.json', null).toPromise().then(data => {
            this.geoCoordMap = data.json();
        });
        this.translate.get('home.homepage.managerportal.config').subscribe((res: any) => {
            this.datas_mon_inc.title.text = res.monthIncome;
            this.datas_mon_inc.legend.data = [res.income];
            this.datas_mon_inc.xAxis[0].data = res.months;
            this.datas_mon_inc.series[0].name = res.income;
            this.datas_reg_sal_stc.title.text = res.regionSaleStatist;
            this.datas_reg_sal_stc.title.subtext = res.regionSaleStatistSub;
            this.datas_reg_sal_stc.series[0].name = res.saleStatistics;
            this.datas_idt_rank.title.text = res.industryRank;
            this.datas_idt_rank.series[0].name = res.industryRank;
            this.datas_pdt_rank.title.text = res.productRank;
            this.datas_pdt_rank.series[0].name = res.productClassify;
            this.datas_pdt_rank.series[1].name = res.BusinessNames;
            this.datas_pdt_sal_stc.title.text = res.productSales;
            this.datas_pdt_sal_stc.xAxis[0].data = res.months;
            this.option.title.text = res.nodeStatist;
        });
        // 月度收入
        const mon_inc_url = this.configService.get('url') + '?service=AdminDashboard&method=getSumBalanceByMonth';
        try {
            this.http.post(mon_inc_url, null).toPromise().then(data => {
                const datas = data.json();
                if (datas.code === '0000') {
                    this.datas_mon_inc.series[0].data = datas.info[0];
                    this.monthIncome.setOption(this.datas_mon_inc);
                } else {
                    console.log('monthIncome_require ERROR***  #code:' + datas.code + '  #info' + datas.message);
                }
            });
        } catch (e) {
            // TODO handle exception
        }
        // 客户节点分布
        const option_url = this.configService.get('url') + '?service=AdminDashboard&method=getCustomerNodeByCity';
        try {
            this.http.post(option_url, null).toPromise().then(data => {
                const datas = data.json();
                if (datas.code === '0000') {
                    this.option.series[0].data = this.convertData(datas.info);
                    this.nodeStatist.setOption(this.option);
                } else {
                    console.log('nodeStatist_require ERROR***  #code:' + datas.code + '  #info' + datas.message);
                }
            });
        } catch (e) {
            // TODO handle exception
        }
        // 战区销售量统计
        const reg_sal_stc_url = this.configService.get('url') + '?service=AdminDashboard&method=getSumBalanceByChnlAndMonth';
        try {
            this.http.post(reg_sal_stc_url, null).toPromise().then(data => {
                const datas = data.json();
                if (datas.code === '0000') {
                    this.datas_reg_sal_stc.series[0].data = datas.info.value;
                    this.datas_reg_sal_stc.xAxis[0].data = datas.info.chnl;
                    this.regionSaleStatist.setOption(this.datas_reg_sal_stc);
                } else {
                    console.log('regionSaleStatist_require ERROR***  #code:' + datas.code + '  #info' + datas.message);
                }
            });
        } catch (e) {
            // TODO handle exception
        }
        // 行业排名
        this.translate.get('home.homepage.managerportal.industry').subscribe((res: any) => {
            const idt_rank_url = this.configService.get('url') + '?service=AdminDashboard&method=getCountByIndustry';
            try {
                this.http.post(idt_rank_url, null).toPromise().then(data => {
                    const datas = data.json();
                    if (datas.code === '0000') {
                        const infos: any = datas.info;
                        infos.forEach((value) => {
                            switch (value.name) {
                                case '0': value.name = res.item0;
                                    break;
                                case '1': value.name = res.item1;
                                    break;
                                case '2': value.name = res.item2;
                                    break;
                                case '3': value.name = res.item3;
                                    break;
                                case '4': value.name = res.item4;
                                    break;
                                case '5': value.name = res.item5;
                                    break;
                                case '6': value.name = res.item6;
                                    break;
                                case '7': value.name = res.item7;
                                    break;
                                case '8': value.name = res.item8;
                                    break;
                                case '9': value.name = res.item9;
                                    break;
                                case '10': value.name = res.item10;
                                    break;
                                case '11': value.name = res.item11;
                                    break;
                                case '12': value.name = res.item12;
                                    break;
                                case '13': value.name = res.item13;
                                    break;
                                case '14': value.name = res.item14;
                                    break;
                                default: value.name = res.item15;
                            }
                        });
                        this.datas_idt_rank.series[0].data = infos;
                        this.industryRank.setOption(this.datas_idt_rank);
                    } else {
                        console.log('industryRank_require ERROR***  #code:' + datas.code + '  #info' + datas.message);
                    }
                });
            } catch (e) {
                // TODO handle exception
            }
        })
        // 产品排名
        const pdt_rank_url = this.configService.get('url') + '?service=AdminDashboard&method=getCountByProduct';
        try {
            this.http.post(pdt_rank_url, null).toPromise().then(data => {
                let dst_csy_data: any = [];
                const bsn_data: any = [];
                const datas = data.json();
                if (datas.code === '0000') {
                    datas.info.forEach(value => {
                        if (value.name === 'productType') { dst_csy_data = value.value; }
                    });

                    dst_csy_data.forEach(value => {
                        datas.info.forEach(val => {
                            if (val.name === value.name) { bsn_data.push.apply(bsn_data, val.value); }
                        });
                    });
                    this.datas_pdt_rank.series[0].data = dst_csy_data;
                    this.datas_pdt_rank.series[1].data = bsn_data;
                    this.productRank.setOption(this.datas_pdt_rank);
                } else {
                    console.log('productRank_require ERROR***  #code:' + datas.code + '  #info' + datas.message);
                }
            });
        } catch (e) {
            // TODO handle exception
        }
        // 渠道销售数据对比
        const chn_sal_cmp_url = this.configService.get('url') + '?service=AdminDashboard&method=getChnlByTop5';
        try {
            this.http.post(chn_sal_cmp_url, null).toPromise().then(data => {
                const datas = data.json();
                if (datas.code === '0000') {
                    this.datas_chn_sal_cmp = datas.info;
                } else {
                    console.log('chnlSales_require ERROR***  #code:' + datas.code + '  #info' + datas.message);
                }
            });
        } catch (e) {
            // TODO handle exception
        }
        // 产品销量统计
        const pdt_sal_stc_url = this.configService.get('url') + '?service=AdminDashboard&method=getSettlementByProduct';
        try {
            this.http.post(pdt_sal_stc_url, null).toPromise().then(data => {
                const datas = data.json();
                if (datas.code === '0000') {
                    const infoArr: Array<string> = [];
                    const infoData: any = [];
                    datas.info.forEach(value => {
                        infoArr.push(value.name);
                        infoData.push({ name: value.name, data: value.value, type: 'bar', stack: value.type });
                    });
                    this.datas_pdt_sal_stc.legend.data = infoArr;
                    this.datas_pdt_sal_stc.series = infoData;
                    this.productSaleStatist.setOption(this.datas_pdt_sal_stc);
                } else {
                    console.log('productSaleStatist_require ERROR***  #code:' + datas.code + '  #info' + datas.message);
                }
            });
        } catch (e) {
            // TODO handle exception
        }
    }
    ngOnInit() {
        // 动态适应窗口大小调整
        window.onresize = () => {
            this.monthIncome.resize();
            this.nodeStatist.resize();
            this.regionSaleStatist.resize();
            this.industryRank.resize();
            this.productRank.resize();
            this.productSaleStatist.resize();
        };
    }
    ngOnDestroy() {
        window.onresize = () => { };
    }
}
